﻿using System;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Wp7Tools.ViewServices {
    public class NavigationService : INavigationService {
        private PhoneApplicationFrame _mainFrame;

        private static INavigationService _defaultInstance = new NavigationService();
        public static INavigationService Default {
            get { return _defaultInstance; }
            set { _defaultInstance = value; }
        }

        public event NavigatingCancelEventHandler Navigating;

        public void NavigateTo(Uri pageUri) {
            string url = pageUri.OriginalString;
            if (url.StartsWith("http") || url.StartsWith("www") || url.StartsWith("mms")) {
                NavigateExternal(pageUri);
            }
            else {
                NavigateInternal(pageUri);
            }
        }

        private void NavigateExternal(Uri pageUri) {
            WebBrowserTask webBrowser = new WebBrowserTask();
            webBrowser.URL = Uri.EscapeDataString(pageUri.ToString());
            webBrowser.Show();
        }

        private void NavigateInternal(Uri pageUri) {
            if (EnsureMainFrame()) {
                _mainFrame.Navigate(pageUri);
            }
        }

        public void GoBack() {
            if (EnsureMainFrame()
                && _mainFrame.CanGoBack) {
                _mainFrame.GoBack();
            }
        }

        private bool EnsureMainFrame() {
            if (_mainFrame != null) {
                return true;
            }
            _mainFrame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (_mainFrame != null) {
                WireNavigatingEvent();
                return true;
            }
            return false;
        }

        private void WireNavigatingEvent() {
            _mainFrame.Navigating += (s, e) => {
                if (Navigating != null) {
                    Navigating(s, e);
                }
            };
        }
    }
}